//
//  NewFeatureViewController.swift
//  Weibo
//
//  Created by 伍银荣 on 2022/1/20.
//  Copyright © 2022 com.WYR. All rights reserved.
//

import UIKit
import SnapKit


//可重用 cellId
private let WBNewFeatureViewCellId = "WBNewFeatureViewCellId"
//新特性图像的数量
private let WBNewFeatureImageCount = 4

class NewFeatureViewController: UICollectionViewController {
    //懒加载属性,必须要在控制器实例化之后才会被创建
   // private lazy var layout = UICollectionViewFlowLayout()
    //MARK: - 构造函数
    init() {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = UIScreen.main.bounds.size
        //设置每行 item 的间距
        layout.minimumInteritemSpacing = 0
        //设置每行 item 中左右两个 item 的间距
        layout.minimumLineSpacing = 0
        //设置水平方向滚动
        layout.scrollDirection = .horizontal
        
        //super.指定的构造函数,完成之后内部属性才会被创建(在此之前的layout常量是用来创建collectionViewController的,它需要用到这个布局. 而collectionView是需要完成 init: 方法后才有的,有collectionView之后,才能在 init: 方法中使用它内部的属性)
        super.init(collectionViewLayout: layout)
       // collectionView.contentSize = CGSize(width: UIScreen.main.bounds.size.width * 4, height: 0)
        //可以分页
        collectionView.isPagingEnabled = true
        //设置每个item的弹性显示
        collectionView.bounces = false
        //不显示水平指示线
        collectionView.showsHorizontalScrollIndicator = false
        //设置内间距
       // collectionView.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //隐藏状态栏(iOS 7.0 开始,就推荐要隐藏状态栏,可以每个控制器分别设置,默认是 NO)
    override var prefersStatusBarHidden: Bool {
        return true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white
        
        //注册可重用 cell - (Register cell classes)
        self.collectionView!.register(NewFeatrueCell.self, forCellWithReuseIdentifier: WBNewFeatureViewCellId)
        
        

    }

    //每个分组中,格子的数量
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return WBNewFeatureImageCount
    }
    
    // MARK: - cell 的显示
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: WBNewFeatureViewCellId, for: indexPath) as! NewFeatrueCell
    
        // Configure the cell
       // cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.green : UIColor.red
        
        cell.imageIndex = indexPath.item
        
        return cell
    }
    
    // MARK: - scrollView 停止滚动方法
    override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        //最后一页调用动画
        //1.通过偏移量拿到当前滚动到的页数
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        //cell 播放动画, 获取 cell
        
        //判断是否是最后一页
        if page != WBNewFeatureImageCount - 1 {
            return
        }
        
        let cell = collectionView.cellForItem(at: NSIndexPath(item: page, section: 0) as IndexPath) as! NewFeatrueCell
        //最后一页显示动画
        cell.showBtnAnim()
    }
    
    //MARK: - scrollViewDelegate 正在滚动
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //获取当前所在页面
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        //获取cell
        let cell = collectionView.cellForItem(at: NSIndexPath(item: page, section: 0) as IndexPath) as? NewFeatrueCell
//        let cell = collectionView.cellForItem(at: NSIndexPath(item: page, section: 0) as IndexPath) as! NewFeatrueCell
        //显示当前页数
        cell?.pageControl.currentPage = page
        //判断是否是最后一页
        if page == WBNewFeatureImageCount - 1 {
           cell?.pageControl.isHidden = true
            return
        }
        //不是最后一页,显示pageControl
        cell?.pageControl.isHidden = false
    }
    
    
    //MARK: - 新特性 cell
    private class NewFeatrueCell: UICollectionViewCell {
        //pageControl
        let pageControl = UIPageControl()
        /// 图像属性
         var imageIndex: Int = 0 {
            didSet {
                iconView.image = UIImage(named: "newFeature_cell_\(imageIndex + 1)")
                //隐藏按钮
                startButton.isHidden = true
                createPageCntrol()
            }
        }
        
        //MARK: - pageControl
        private func createPageCntrol() {
            pageControl.isHidden = false
            //frame: CGRect(x: 0, y: self.bounds.height - 100, width: self.bounds.width, height: 40)
            
            pageControl.numberOfPages = WBNewFeatureImageCount
           // pageControl.currentPage = 0
            pageControl.currentPageIndicatorTintColor = .white
            pageControl.pageIndicatorTintColor = .darkGray
            
            pageControl.backgroundColor = .red
            
            self.addSubview(pageControl)
            
            pageControl.snp_makeConstraints { (make) in
                            make.centerX.equalTo(self.snp_centerX)
                                make.bottom.equalTo(self.snp_bottom).multipliedBy(0.95)
                                make.width.equalTo(self.snp_width)
                                make.height.equalTo(20)
                            }
        }
        
        //点击开始体验按钮
        @objc private func clickStartButton() {
            print("开始体验")
        }
        
        /// 显示按钮动画
        func showBtnAnim() {
            startButton.isHidden = false
            startButton.transform = CGAffineTransform(scaleX: 0, y: 0)
            //动画开启前进制按钮的用户交互
            startButton.isUserInteractionEnabled = false
            UIView.animate(withDuration: 1.3,              // 动画时长
                           delay: 0,                       // 延迟时间
                           usingSpringWithDamping: 0.8,    // 弹力系数, 0~1, 越小越弹
                           initialSpringVelocity: 10,      // 初始速度,模拟重力加速度.(默认是9.8)
                           options: [],                    // 动画选项
                           animations: { () -> Void in //动画闭包
                            self.startButton.transform = CGAffineTransform.identity
            }
                , completion: { (_) in
                    //动画结束后开启与用户交互
                    self.startButton.isUserInteractionEnabled = true
            })
        }
        
        //frame 的大小是根据 layout.itemSize 指定的
        override init(frame: CGRect) {
            super.init(frame: frame)
          //  print(frame)
            
            setupUI()
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        private func setupUI() {
           //1.添加控件
            addSubview(iconView)
            addSubview(startButton)
            
            //不能单纯在此设置隐藏(会导致 cell 的复用问题)
            startButton.isHidden = true
            
            //2.指定位置
            iconView.frame = bounds
            
            startButton.snp_makeConstraints { (make) in
                make.centerX.equalTo(self.snp_centerX)
                make.width.equalTo(180)
                make.height.equalTo(50)
                make.bottom.equalTo(self.snp_bottom).multipliedBy(0.7)
            }
            
            startButton.addTarget(self, action: #selector(clickStartButton), for: .touchUpInside)
        }
        
        //MARK: - 懒加载控件
        //图像
        private lazy var iconView: UIImageView = UIImageView()
        //按钮
        private lazy var startButton: UIButton = UIButton(title: "开始体验", titleColor: UIColor.white, btnBackgroundColor : .orange)
        
    }
    
    
    
    
    
    
    
    
    

    // MARK: UICollectionViewDelegate

    /*
    // Uncomment this method to specify if the specified item should be highlighted during tracking
    override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
        return true
    }
    */

    /*
    // Uncomment this method to specify if the specified item should be selected
    override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        return true
    }
    */

    /*
    // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
    override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
        return false
    }

    override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
        return false
    }

    override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
    
    }
    */

}
